//
//  CGFloatExtensions.swift
//  SwiftExtensionDemo
//
//  Created by 腾億 on 2017/11/30.
//  Copyright © 2017年 tml. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit

extension CGFloat {
    //返回CGFloat的中心值
    public var center: CGFloat { return (self / 2) }
    
    @available(*, deprecated: 1.8, renamed: "degreesToRadians")
    public func toRadians() -> CGFloat {
        return (.pi * self) / 180.0
    }
    
    public func degreesToRadians() -> CGFloat {
        return (.pi * self) / 180.0
    }
    
    public mutating func toRadiansInPlace() {
        self = (.pi * self) / 180.0
    }
    //将角度转换为弧度
    public static func degreesToRadians(_ angle: CGFloat) -> CGFloat {
        return (.pi * angle) / 180.0
    }
    //将弧度转换为度数
    public func radiansToDegrees() -> CGFloat {
        return (180.0 * self) / .pi
    }
    //将角度弧度转换为度数 可变的版本
    public mutating func toDegreesInPlace() {
        self = (180.0 * self) / .pi
    }
    //将角度弧度转换为度数 静态版本
    public static func radiansToDegrees(_ angleInDegrees: CGFloat) -> CGFloat {
        return (180.0 * angleInDegrees) / .pi
    }
    //返回0.0到1.0之间的随机浮点数
    public static func random() -> CGFloat {
        return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
    }
    //返回范围为min ... max（含）的随机浮点数
    public static func random(within: Range<CGFloat>) -> CGFloat {
        return CGFloat.random() * (within.upperBound - within.lowerBound) + within.lowerBound
    }
    
    public static func random(within: ClosedRange<CGFloat>) -> CGFloat {
        return CGFloat.random() * (within.upperBound - within.lowerBound) + within.lowerBound
    }
    //返回两个角度之间的最短角度。 结果总是在两者之间:-π和π
    public static func shortestAngleInRadians(from first: CGFloat, to second: CGFloat) -> CGFloat {
        let twoPi = CGFloat(.pi * 2.0)
        var angle = (second - first).truncatingRemainder(dividingBy: twoPi)
        if angle >= .pi {
            angle -= twoPi
        }
        if angle <= -.pi {
            angle += twoPi
        }
        return angle
    }
}
#endif
